package org.chengyi.model_shop.controller;

import com.github.pagehelper.PageInfo;
import jakarta.servlet.http.HttpServletRequest;
import org.chengyi.model_shop.entity.Product;
import org.chengyi.model_shop.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@RestController
@RequestMapping
public class ProductController {
    @Autowired
    private ProductService productService;

    @GetMapping("/pageProduct")
    public PageInfo<Product> getProductList(@RequestParam(defaultValue = "1") int pageNum,
                                            @RequestParam(defaultValue = "8") int pageSize,
                                            @RequestParam(required = false) Integer categoryId) {
        return productService.getProductList(pageNum, pageSize, categoryId);
    }


    @PostMapping("/api/upload")
    public Map<String, Object> uploadImage(@RequestParam("image") MultipartFile file) {
        Map<String, Object> result = new HashMap<>();
        if (file.isEmpty()) {
            result.put("success", false);
            result.put("message", "文件为空");
            return result;
        }
        try {
            String uploadDir = System.getProperty("user.dir") + "/uploads/";
            File dir = new File(uploadDir);
            if (!dir.exists()) dir.mkdirs();

            String filename = System.currentTimeMillis() + "_" + file.getOriginalFilename();
            File dest = new File(dir, filename);
            file.transferTo(dest);

            String imageUrl = "/uploads/" + filename;
            result.put("success", true);
            result.put("url", imageUrl);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "上传失败");
        }
        return result;
    }

    @PostMapping("/api/products")
    public Map<String, Object> addProduct(@RequestBody Product product) {
        return productService.addProduct(product);
    }

    @GetMapping("getByName")
    public List<Product> getByName(@RequestParam String name) {
        return productService.getByName(name);
    }

    @DeleteMapping("delete")
    public String delete(@RequestParam Integer id) {
        return productService.delete(id);
    }

    @GetMapping("getById")
    public Product getById(@RequestParam Integer id) {
        return productService.getById(id);
    }

    @PutMapping("update")
    public Map<String, Object> update(@RequestBody Product product) {
        return productService.update(product);
    }

    @GetMapping("getDescriptionById")
    public String getDescriptionById(@RequestParam Integer id) {
        return productService.getDescriptionById(id);
    }
}
